#ifndef DPI_C
#define DPI_C

#include <svdpi.h>
#include <veriuser.h>
#include <vpi_user.h>

typedef struct {
	unsigned char c;
} cnt_s;

void* create_counter()
{
	cnt_s* counter = (cnt_s*) malloc(sizeof(cnt_s)); // 分配存储空间
	counter->c = 0;
	return counter;
}

void do_count(
	cnt_s *counter,
	svLogicVecVal* o,
	const svLogicVecVal* i,
	const svLogic reset,
	const svLogic load)
{
	if ((reset == sv_z) || (reset == sv_x) || // 检查标量reset
		(load  == sv_z) || (load  == sv_x) || // 检查标量load
		(i->bval == 1))                       // 检查向量i
	{
		io_printf("Error: z or x detected on input\n");
		vpi_control (vpiFinish, 0);
	}

	if (reset) counter->c = 0;           // 复位
	else if (load) counter->c = i->aval; // 加载预设值
	else counter->c++;                   // 计数
	o->aval = counter->c & 0xf;          // 屏蔽高位
	o->bval = 0;
	io_printf("C: o=%x, i=%x, reset=%x, load=%x\n", o->aval, i->aval, reset, load);
}

#endif
